package com.kevin.Code.Tree;

/**
 * @author Vinlee Xiao
 * @Classname BalancedBinaryTree
 * @Description Leetcode 110. 平衡二叉树 简单题
 * @Date 2022/1/10 22:21
 * @Version 1.0
 */
public class BalancedBinaryTree {

    /**
     * 平衡二叉树
     *
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        //递归结束
        if (root == null) {
            return true;
        }

        boolean isBalancedOfLeft = isBalanced(root.left);
        boolean isBalancedOfRight = isBalanced(root.right);

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        //满足条件
//        if (isBalancedOfLeft && isBalancedOfLeft && Math.abs(leftHeight - rightHeight) <= 1) {
//            return true;
//        }
        return isBalancedOfLeft && isBalancedOfRight && (Math.abs(leftHeight - rightHeight) <= 1);
    }

    /**
     * @param root
     * @return
     */
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = getHeight(root.left);
        int right = getHeight(root.right);
        //返回最大的深度
        return Math.max(left, right) + 1;

    }
}
